<?php
declare(strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\model\{CouponOrder, User};
use app\service\{JutuikeService, LogService};

class SyncJutuikeOrder extends Command
{
    protected function configure()
    {
        $this->setName('sync:jutuike_order')
            ->setDescription('Sync orders from Jutuike');
    }
    
    protected function execute(Input $input, Output $output)
    {
        try {
            $service = new JutuikeService();
            
            // 获取待同步的订单
            $orders = CouponOrder::where([
                'service_id' => 1, // 聚推客
                'status' => 0
            ])->select();
            
            $count = 0;
            foreach ($orders as $order) {
                try {
                    // 同步订单状态
                    $result = $service->syncOrderStatus($order->order_no);
                    
                    if ($result['success']) {
                        // 更新订单状态
                        $order->status = $result['data']['status'];
                        $order->settlement_time = $result['data']['settlement_time'];
                        $order->save();
                        
                        // 如果订单已结算，给用户分佣
                        if ($order->status == 2) {
                            $this->settleCommission($order);
                        }
                        
                        $count++;
                    }
                    
                } catch (\Exception $e) {
                    LogService::error('SyncJutuikeOrder', sprintf(
                        'Sync order failed: %s, order_no: %s',
                        $e->getMessage(),
                        $order->order_no
                    ));
                }
            }
            
            $output->writeln(sprintf('Successfully synced %d orders', $count));
            
        } catch (\Exception $e) {
            LogService::error('SyncJutuikeOrder', sprintf(
                'Sync orders failed: %s',
                $e->getMessage()
            ));
            $output->writeln('<error>' . $e->getMessage() . '</error>');
        }
    }
    
    /**
     * 结算佣金
     */
    protected function settleCommission(CouponOrder $order)
    {
        // 获取用户信息
        $user = User::find($order->user_id);
        if (!$user) {
            throw new \Exception('User not found');
        }
        
        // 更新用户余额
        $user->balance += $order->merchant_commission;
        $user->save();
        
        // 记录余额变动
        \app\model\UserBalanceFlow::create([
            'merchant_id' => $order->merchant_id,
            'user_id' => $user->id,
            'order_no' => $order->order_no,
            'type' => 5, // 分佣
            'balance_change' => $order->merchant_commission,
            'balance_before' => $user->balance - $order->merchant_commission,
            'balance_after' => $user->balance,
            'create_time' => date('Y-m-d H:i:s')
        ]);
    }
} 